String.prototype.len = function() {
  return this.length;
  
  /* count for utf-8
  var realLen = 0;
  for (var i = 0; i < this.length; i++) {
    var c = this.charCodeAt(i);
    if (c <= 0x7f) {
      realLen += 1;
    } else if (c >= 0x80 && c <= 0x7ff) {
      realLen += 2;
    } else {
      realLen += 3;
    }
  }
  return realLen;
  */
  
  /* count for gbk
  return this.replace(/[^\x00-\xff]/g, "**").length;
  */
}

function setMaxLength(object, maxLength) {
  var objValue = object.value;
  var finalLength = objValue.len();

  if (finalLength > maxLength) {
    while (finalLength > maxLength) {
      objValue = objValue.substr(0, objValue.length - 1);
      finalLength = objValue.len();
    }

    object.value = objValue;
  }

  document.getElementById(object.id + "size").innerHTML = maxLength - finalLength;
}

function setMaxLengthForPaste(object, maxLength) {
  if(document.selection) {
    if(document.selection.createRange().parentElement().id == object.id) {
      selLength = document.selection.createRange().text.len();
    }
  }

  var clipValue = window.clipboardData.getData("Text");
  var finalLength = object.value.len() + clipValue.len() - selLength;

  if (finalLength > maxLength) {
    while (finalLength > maxLength) {
      clipValue = clipValue.substr(0, clipValue.length - 1);
      finalLength = object.value.len() + clipValue.len() - selLength;
    }

    if (clipValue.len() <= 0) {
      window.event.returnValue=false;
    } else {
      window.clipboardData.setData("Text", clipValue);
      window.event.returnValue = true;
    }
  }

  document.getElementById(object.id + "size").innerHTML = maxLength - finalLength;
}

function doPress(e) {
  var ele;
  var maxLen;

  if (typeof(window.event) != "undefined" ) {
    //IE
    ele = e.srcElement;
    maxLen = ele.length;
  } else {
    //FF
    ele = e.target;
    maxLen = ele.getAttribute("length");
  }

  if (ele.type == "text" || ele.type == "textarea") {
    if (maxLen != null) {
      setMaxLength(ele, maxLen);
    }
  }
}

function doPaste(e) {
  var ele;
  var maxLen;

  if (typeof(window.event) != "undefined" ) {
    //IE
    ele = e.srcElement;
    maxLen = ele.length;
  } else {
    //FF
    ele = e.target;
    maxLen = ele.getAttribute("length");
  }

  if (ele.type == "text" || ele.type == "textarea") {
    if (maxLen != null) {
      setMaxLengthForPaste(ele, maxLen);
    }
  }
}

if (typeof(window.addEventListener) != "undefined") {
  //FF
  document.documentElement.addEventListener("keyup", doPress, false);
  document.documentElement.addEventListener("input", doPress, false);
} else {
  //IE
  document.documentElement.attachEvent('onkeyup', doPress);
  document.documentElement.attachEvent('onpaste', doPaste);
}
